package com.jinsilu.freight.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.hjq.base.BaseDialog;
import com.hjq.http.EasyHttp;
import com.hjq.http.exception.ResultException;
import com.hjq.http.listener.HttpCallback;
import com.jinsilu.freight.R;
import com.jinsilu.freight.common.MyVBActivity;
import com.jinsilu.freight.databinding.ActivityOrderDetailsBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.helper.ReplaceHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.BackCardDefaultApi;
import com.jinsilu.freight.http.request.GetDrivingLicenseApi;
import com.jinsilu.freight.http.request.GetIdCardApi;
import com.jinsilu.freight.http.request.GetVehicleListApi;
import com.jinsilu.freight.http.request.TakeOrderApi;
import com.jinsilu.freight.http.response.BankInfoBean;
import com.jinsilu.freight.http.response.ContractBean;
import com.jinsilu.freight.http.response.DrivingLicenseBean;
import com.jinsilu.freight.http.response.IdCardBean;
import com.jinsilu.freight.http.response.OrderDetailsBean;
import com.jinsilu.freight.http.response.VehicleListBean;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.jinsilu.freight.ui.dialog.WebViewDialog;
import com.jinsilu.freight.ui.fragment.UnfinishedWaybillFragment;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


/**
 * 运单详情
 */
public class SourceMallDetailsActivity extends MyVBActivity<ActivityOrderDetailsBinding> {

    private String toNumber;
    private OrderDetailsBean mOrderDetails;

    @Override
    protected void initView() {
        toNumber = getIntent().getStringExtra("toNumber");
        getOrderDetailsList(toNumber);
    }

    @Override
    protected void initData() {
        binding.orderContactImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mOrderDetails && !TextUtils.isEmpty(mOrderDetails.getConsignorPhone())) {
                    PhoneUtils.dial(mOrderDetails.getConsignorPhone());
                }
            }
        });

        binding.takeOrderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonHelper.isLogin()) {
                    CommonHelper.goLoin();
                    return;
                }
                if (1 != CommonHelper.getCertificationStatus()) {
                    toast("认证后方可操作");
                    return;
                }
                checkBackCard();
            }
        });
    }


    private void checkBackCard() {

        // 查询银行卡信息
        EasyHttp.get(this)
                .api(new BackCardDefaultApi())
                .request(new HttpCallback<HttpData<BankInfoBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<BankInfoBean> data) {
                        checkBackCardInfo(data.getData());
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        if (e instanceof ResultException) {
                            new MessageDialog.Builder(getContext())
                                    // 标题可以不用填写
                                    .setTitle("提示")
                                    // 内容必须要填写
                                    .setMessage("暂无默认银行卡,请先绑定银行卡后再继续操作！")
                                    // 确定按钮文本
                                    .setConfirm("绑卡")
                                    // 设置 null 表示不显示取消按钮
                                    //.setAutoDismiss(false)
                                    .setListener(new MessageDialog.OnListener() {

                                        @Override
                                        public void onConfirm(BaseDialog dialog) {
                                            startActivity(MyBankManageActivity.class);
                                        }

                                        @Override
                                        public void onCancel(BaseDialog dialog) {
                                            takeOrders(toNumber,"0");
                                        }
                                    })
                                    .show();
                        }
                    }

                });
    }

    private void checkBackCardInfo(BankInfoBean bankInfoBean){
        if(
                TextUtils.isEmpty(bankInfoBean.getAccountHolderPhone()) ||
                TextUtils.isEmpty(bankInfoBean.getIdentityCardFrontImg()) ||
                TextUtils.isEmpty(bankInfoBean.getIdentityCardReverseImg())
        ){
            new MessageDialog.Builder(getContext())
                    // 标题可以不用填写
                    .setTitle("提示")
                    // 内容必须要填写
                    .setMessage("银行卡信息缺少，请补充缺失信息！")
                    // 确定按钮文本
                    .setConfirm("补充信息")
                    // 设置 null 表示不显示取消按钮
                    //.setAutoDismiss(false)
                    .setListener(new MessageDialog.OnListener() {

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            Intent intent = new Intent(getContext(),MyBankEditActivity.class);
                            intent.putExtra("bankInfo",bankInfoBean);
                            startActivity(intent);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                        }
                    })
                    .show();
        }else {
            showBackCardConfirmDialog(bankInfoBean);
        }

    }

    private void showBackCardConfirmDialog(BankInfoBean bankInfoBean){
        // 自定义对话框®
        BaseDialog baseDialog = new BaseDialog.Builder(this)
                .setContentView(R.layout.dialog_default_bank_confirm)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .show();

        ((TextView)baseDialog.findViewById(R.id.tv_bank_name)).setText(bankInfoBean.getBankName());
        ((TextView)baseDialog.findViewById(R.id.et_user_name)).setText(bankInfoBean.getAccountHolder());
        ((TextView)baseDialog.findViewById(R.id.et_id_card_number)).setText(ReplaceHelper.iDCardFormat(bankInfoBean.getIdentityCard()));
        ((TextView)baseDialog.findViewById(R.id.et_bank_card_number)).setText(ReplaceHelper.bankCardFormat(bankInfoBean.getBankCard()));


        baseDialog.findViewById(R.id.btn_submit_one).setOnClickListener(view -> {
            startActivity(MyBankManageActivity.class);
            baseDialog.dismiss();
        });

        baseDialog.findViewById(R.id.btn_submit_two).setOnClickListener(view -> {
            takeOrders(toNumber,"1");
            baseDialog.dismiss();
        });


    }

    private void takeOrders(String toNumber,String confirmBank) {
        // 检查运价是否为0
        if (mOrderDetails != null && mOrderDetails.getSettlePrice() > 1) {
            getIdCardStatus(confirmBank);
            return;
        }
        executeTakeOrder(toNumber, confirmBank);
    }

    /**
     * 获取身份验证状态
     */
    private void getIdCardStatus(String confirmBank) {
        EasyHttp.get(this)
                .api(new GetIdCardApi())
                .request(new HttpCallback<HttpData<IdCardBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<IdCardBean> data) {
                        getVehicleList(confirmBank,data.getData());
                    }
                });
    }



    private void getVehicleList(String confirmBank,IdCardBean idCardBean) {
        // 车辆列表
        EasyHttp.get(this)
                .api(new GetVehicleListApi().setPageNum(String.valueOf(1)).setPageSize("1"))
                .request(new HttpCallback<HttpData<VehicleListBean>>(this) {

                    @Override
                    public void onSucceed(HttpData<VehicleListBean> data) {
                        List<VehicleListBean> vehicleListBeans = data.getRows();
                        showAgreeDialog(confirmBank,idCardBean,vehicleListBeans.get(0));
                    }
                });
    }

    private void showAgreeDialog(String confirmBank,IdCardBean idCardBean , VehicleListBean vehicleListBean){
        try {


            new WebViewDialog.Builder(this)
                    .setTitle("协议签署")
                    .setHtmlContent(getContext(),mOrderDetails,idCardBean,vehicleListBean)
                    .setListener(new WebViewDialog.OnListener() {
                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            executeTakeOrder(toNumber, confirmBank);
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            // 用户取消，不做任何操作
                        }
                    })
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void executeTakeOrder(String toNumber, String confirmBank) {
        // 接单
        EasyHttp.post(this)
                .api(new TakeOrderApi()
                        .setOrderNumber(toNumber)
                        .setConfirmBank(confirmBank)
                )
                .request(new HttpCallback<HttpData<ContractBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ContractBean> data) {
                        toast(data.getMessage());
                        BusUtils.postSticky(UnfinishedWaybillFragment.TAG_NEED_TO_REFRESH_WAYBILL); // UnfinishedWaybillFragment will receive
                        finish();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        if (e instanceof ResultException) {
                            ResultException resultException = (ResultException) e;
                            HttpData<String> httpData = resultException.getData();
                            if (303 == httpData.getCode()) {
                                BrowserActivity.start(getActivity(), httpData.getMessage());
                            } else {
                                toast(httpData.getMessage());
                            }
                        }
                    }

                });
    }

    private void getOrderDetailsList(String toNumber) {
        // 获取货源列表
        EasyHttp.get(this)
                .api(String.format("api/order/%s", toNumber))
                .request(new HttpCallback<HttpData<OrderDetailsBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<OrderDetailsBean> data) {
                        mOrderDetails = data.getData();
                        setContentTxt(mOrderDetails);
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        binding.orderEmptyView.getRoot().setVisibility(View.VISIBLE);
                    }
                });
    }

    /**
     * 填充详情数据
     */
    private void setContentTxt(OrderDetailsBean data) {

        binding.orderNumber.setText(String.format("%s", data.getOrderNumber()));
        binding.orderCreateCompany.setText(String.format("%s", data.getPartnerName()));
        binding.orderCreatePerson.setText(String.format("%s", data.getCreateBy()));
        binding.deliveryAddress.setText(String.format("%s", data.getConsignorAddress()));
        binding.deliveryAddress.setSelected(true);
        binding.consignorName.setText(String.format("%s", TextUtils.isEmpty(data.getConsignorName()) ? "" : data.getConsignorName()));
        binding.consignee.setText(String.format("%s", TextUtils.isEmpty(data.getConsigneeName()) ? "" : data.getConsigneeName()));
        binding.shippingAddress.setText(String.format("%s", data.getConsigneeAddress()));
        binding.shippingAddress.setSelected(true);
        binding.freightRate.setText(String.format(Locale.getDefault(), "%s元/吨", data.getSettlePrice()));

        binding.productName.setText(String.format("%s", data.getGoodsName()));
        binding.productPrice.setText(String.format("%s元/吨", data.getPurchasePrice()));
        binding.orderRemark.setText(TextUtils.isEmpty(data.getRemarks()) ? "无" :
                TextUtils.isEmpty(data.getRemarks().trim()) ? "无" : data.getRemarks());
        binding.createTime.setText(String.format("%s", TextUtils.isEmpty(data.getCreateTime()) ? "" : data.getCreateTime()));
    }
}
